package com.seal.yoyoshop.web;

import com.seal.yoyoshop.bin.Goods;
import com.seal.yoyoshop.bin.Item;
import com.seal.yoyoshop.bin.Order;
import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.GoodsService;
import com.seal.yoyoshop.service.OrderService;
import com.seal.yoyoshop.service.impl.GoodsServiceImpl;
import com.seal.yoyoshop.service.impl.OrderServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "AddToCertServlet", value = "/index/addToCart")
public class AddToCertServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();
    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            response.getWriter().append("login");
        }else {
            String goodsIdstr = request.getParameter("goodid");
            int goodsId = Integer.parseInt(goodsIdstr);
//            获取库存
            Goods goods = goodsService.getGoodById(goodsId);
            int stock = goods.getStock();
            if(stock <= 0) response.getWriter().append("empty");
            else {
                Order tempOrder = (Order)session.getAttribute("order");
                if(tempOrder == null){
                    tempOrder = new Order();
                    tempOrder.setUserId(user.getId());
                    List<Item> itemList = new ArrayList<>();
                    tempOrder.setItemList(itemList);
                    tempOrder.setAmount(0);
                    tempOrder.setTotal(0.0);
                    session.setAttribute("order",tempOrder);
                }

                orderService.addGoodsToOrder(goods, tempOrder);
                response.getWriter().append("ok");
            }
        }

    }
}
